from flask import Flask,request,abort,make_response,render_template,url_for
import hashlib
import xmltodict
import time
import json
from Sign import Sign
WECHAT_TOKEN="super"
app=Flask(__name__)


@app.route('/',methods=["GET","POST"])
def index():

    if request.method=="GET":
        singnature=request.args.get("signature")
        timestamp=request.args.get("timestamp")
        nonce=request.args.get("nonce")
        echostr=request.args.get("echostr")
        data=request.data

        if timestamp==None:
                timestamp="xxxx"
        if nonce==None:
            nonce="yyyy"

        WECHAT_TOKEN="super"
        li=[WECHAT_TOKEN,timestamp,nonce]
       
        li.sort()
        sha1=hashlib.sha1()
        map(sha1.update,li)
        hashcode=sha1.hexdigest()

        # if hashcode==singnature:
        #     return echostr
        # else:
        #     return "error"
        return render_template("indexs.html",timestamp=timestamp,nonceStr=nonce,signature=singnature)
    if request.method=="POST":
        xml_str=request.data
        xml_dict=xmltodict.parse(xml_str)
        xml_dict=xml_dict.get("xml")
        content=""
        if xml_dict.get("Content")=="你好":
            content="您也好的呀！！！！"
        if xml_dict.get("Content")=="吃了没":
            content="我也没有吃的了呢！！！！"
        resp_dict={
                    "xml":{
                        "ToUserName":xml_dict.get("FromUserName"),
                        "FromUserName":xml_dict.get("ToUserName"),
                        "CreateTime":int(time.time()),
                        "MsgType":"text",
                        "Content":content
                    }
                }
        resp_xml_str=xmltodict.unparse(resp_dict)
        return resp_xml_str      


@app.route('/jssdk',methods=["GET"])
def jssdk():
    html_url=url_for("jssdk")
    ticket="19_LxvzhOXJxolhACnviwH9O14JiNDGYY0SOcuqNA1wP7YQ9PUxHXiqMqgi3yIsU4xEHKwYhHcGaVvHHVa-WgzAvDyhno9VvXlJxBCqYCWe7DLHWXv5GcWhRit87xXcltUPXez0XzgA5_2pZsfAMMAeAFAHHV"
    sign=Sign(ticket,html_url)
    result={
        "result":sign.sign()
    }
    response_header={
        'Access-Control-Allow-Origin' : '*'
    }
    
    json_dict= json.loads(make_response(json.dumps(result).encode("utf-8"),200,response_header))
    result=json_dict["result"]
    timestamp=result[timestamp]
    nonceStr=result[nonceStr]
    signature=result[signature]

    return render_template("indexs.html",timestamp=timestamp,nonceStr=nonceStr,signature=signature)

if __name__ == "__main__":
    app.run(host="127.0.0.1",port=80,debug=True)